﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using WebSupergoo.ABCpdf8;

namespace Stackoverflow_Reader
{
    public partial class Form1 : Form
    {
        private Parser p;
        private Doc finalDocument = new Doc();
        private bool finished = false;
        private int qnum = 0, qnumall = 0;
        private int line_ind = 0;
        private object locker = new object();
        private BackgroundWorker backgroundWorker = new BackgroundWorker();


        public Form1()
        {
            InitializeComponent();

            backgroundWorker.DoWork += new DoWorkEventHandler(worker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                if (numericUpDown1.Value != 0)
                {
                    if (backgroundWorker1.IsBusy == false)
                    {
                        line_ind = 0;
                        qnum = 0;
                        progressBar1.Maximum = Convert.ToInt32(numericUpDown1.Value);
                        ThreadStarter();
                        numericUpDown1.Enabled = false;
                        textBox1.Enabled = false;
                        checkBox1.Enabled = false;
                        chbTitle.Enabled = false;
                        qnum = 0;
                        qnumall = 0;
                        finished = false;
                    }
                    else
                    {
                        MessageBox.Show("Work in progress, Please wait...", "Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Number of questions can not be 0.", "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Keywords not entered, plese enter least one keyword", "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }

        //------------------------------------------------------------------------------------------------------------------------
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Doc doc = e.Result as Doc;
            if (doc != null)
                finalDocument.Append(doc);
            finalDocument.SetInfo(finalDocument.Root, "/OpenAction", "<< /Type /Action /S /Named /N /Print >>");
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            string PDFFolder = appPath + @"\PDFs";

            if (!Directory.Exists(PDFFolder))
            {
                Directory.CreateDirectory(PDFFolder);
            }

            string fullFilename = PDFFolder + @"\current.pdf";


            finalDocument.Save(fullFilename);
            qnum = 0;
            if (line_ind < textBox1.Lines.Length && !finished)
            {
                ThreadStarter();
            }
            else
            {
                MessageBox.Show("Done.");
                textBox1.Enabled = true;
                checkBox1.Enabled = true;
                chbTitle.Enabled = true;
                numericUpDown1.Enabled = true;
                finished = true;
                progressBar1.Value = 0;
                Process pr = new Process();
                pr.StartInfo.FileName = fullFilename;
                pr.Start();
            }
        }

        //------------------------------------------------------------------------------------------------------------------------
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<question> links;

            try
            {
                links = p.GetLinks();
                if (links.Count > 0)
                    e.Result = p.GetQuestions(links);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //------------------------------------------------------------------------------------------------------------------------
        private delegate void pr_bar();

        private void p_QuestionParsed(object sender, EventArgs e)
        {
            progressBar1.Invoke(new pr_bar(Perform_Step));
        }


        //------------------------------------------------------------------------------------------------------------------------
        private void Perform_Step()
        {
            progressBar1.PerformStep();

            qnum++;
            qnumall++;
            label4.Text = qnum.ToString();
            label7.Text = qnumall.ToString();
            if (finished)
                p.isContinue = false;
        }


        //------------------------------------------------------------------------------------------------------------------------
        private void ThreadStarter()
        {
            qnum = 0;


            progressBar1.Value = 0;
            p = new Parser(checkBox1.Checked, Convert.ToInt32(numericUpDown1.Value), textBox1.Lines[line_ind],
                           chbTitle.Checked);
            p.QuestionParsed += new EventHandler(p_QuestionParsed);
            label3.Text = textBox1.Lines[line_ind];

            //Monitor.Enter(backgroundWorker1);
            backgroundWorker.RunWorkerAsync(textBox1.Lines[line_ind]);

            line_ind++;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            finished = true;
        }
    }
}